import {
  createResponseComposition,
  context,
  rest,
  ResponseResolver,
  setupWorker,
  response,
  ResponseFunction,
  RestContext,
  DefaultBodyType,
  RestRequest,
  PathParams,
} from 'msw';
import db from '~/DB';
import { getToken, getTokenInfo } from '../utils/token';
import { Token } from '~~/DB/types/token.d';
import { Status } from '~~/DB/types/status.d';
import { defineResponseResolver } from '../define';

// interface Req extends T {
//   token?: string;
//   tokenInfo?: Token;
// }

// export const validateToken = async (
//   req: Req,
//   callback: () => any,
//   opts: Record<string, unknown> = {},
// ) => {
//   const tokenInfo = await getTokenInfo(req);
//   if (
//     !tokenInfo ||
//     tokenInfo.status === Status.disable ||
//     Date.now() > tokenInfo.expirationTime.getTime()
//   ) {
//     return response(
//       context.status(401),
//       context.json({ message: 'token已失效, 请重新登录' }),
//     );
//   }
//   return callback();
// };
type T = Parameters<typeof rest['all']>[1];
// type T = ResponseResolver<
//   RestRequest<DefaultBodyType, PathParams>,
//   RestContext,
//   DefaultBodyType
// >;
// type T = ResponseResolver<
//   RestRequest<RequestBodyType, Params>,
//   RestContext,
//   ResponseBody
// >;

export const validateToken =
  (resolver: T): T =>
  async (req, res, ctx) => {
    const tokenInfo = await getTokenInfo(req);
    if (
      !tokenInfo ||
      tokenInfo.status === Status.disable ||
      Date.now() > tokenInfo.expirationTime.getTime()
    ) {
      return res(
        ctx.status(401),
        ctx.json({ message: 'token已失效, 请重新登录' }),
      );
    }
    return resolver(req, res, ctx);
  };
